// # StringJoiner

//更高效拼接String,应该使用StringBuilder

//很多时候，我们拼接的String像这样
// Hello Bob,Alice,Grace!
public class Main {
	public static void main(String[] args) {
		String[] names = {"Bob","Alice","Grace"};

		var sb = new StringBuilder();
		sb.append("Hello ");
		for (String name : names) {
			sb.append(name).append(",");
		}
		//注意去掉最后的","
		sb.delete(sb.length() - 1,sb.length());
			//删除区间
		sb.append("!");
		System.out.println(sb.toString());

	}
}


//类似用'分隔符'拼接[数组]的需求很常见，所以Java标准库还提供了一个StringJoiner来干这个事：
import java.util.StringJoiner;

public class Main {
	public static void main(String[] args) {
		String[] names = {"Bob","Alice","Grace"};
		var sj = new StringJoiner(", ");

		for (String name : names) {
			sj.add(name);
		}

		System.out.println(sj.toString());

	}
}

//慢着！用StringJoiner的结果少了前面的"Hello "和结尾的"!"！遇到这种情况，需要给StringJoiner指定“开头”和“结尾”：
import java.util.StringJoiner;

public class Main {
    public static void main(String[] args) {
        String[] names = {"Bob", "Alice", "Grace"};
        var sj = new StringJoiner(", ", "Hello ", "!"); //StringJoiner("分隔符","Header","Endness")
        for (String name : names) {
            sj.add(name);
        }
        System.out.println(sj.toString());
    }
}

//那么StringJoiner内部是如何拼接字符串的呢？如果查看源码，可以发现，StringJoiner内部实际上就是使用了StringBuilder，所以拼接效率和StringBuilder几乎是一模一样的。


// String.join()
//String还提供了一个静态方法join()，这个方法在内部使用了StringJoiner来拼接字符串，在不需要指定“开头”和“结尾”的时候，用String.join()更方便：
String[] names = {"Bob","Alice","Grace"};
var s = String.join(", ", names);


//练习
// 请使用StringJoiner构造一个Select语句
import java.util.StringJoiner;

public class Main {
	public static void main(String[] args) {
		String[] fields = {"name","position","salary" };
		String table = "employee";
		String select = buildSelectSql(table,fields);
		System.out.println(select);
		System.out.println("Select name,position,salary From employee".equals(select) ? "测试成功" : "测试失败");
	}

	static String buildSelectSql(String table, String[] fields) {
		// TODO:
		var sj = new StringJoiner(",","Select "," From employee");

		for (String n : fields) {
			sj.add(n);
		}

		return sj.toString();
	}
}


/*  小结

用'指定分隔符'拼接String[]时，使用StringJoiner或者String.join()更方便；

用StringJoiner拼接字符串时，还可以额外附加一个“开头Header”和“结尾Tail”。

*/



























